"use strict";

angular.module('app.sensor').controller('DeviceCtrl',function ($scope,$http,$cookieStore) {
    $scope.fid = $cookieStore.get('userinfo').fid;
    $scope.insert = {};
    $scope.type_obj = {};
	// 设备类型
	$http.get(baseurl+'/device_types').then(function(res){
       // console.log(res.data);
       if (res.data.ret == 1) {
       	  $scope.types = res.data.info;
       	  if (res.data.info.length > 0) {
             $scope.first_type = res.data.info[0].id;
             for (var i = 0; i < res.data.info.length; i++) {
             	var obj = res.data.info[i];
             	$scope.type_obj[obj.id] = obj.name;
             }
             
       	  }
       }
	});
	// 端口号（哪种协议）
	$http.get(baseurl+'/select_ports').then(function(res){
		// console.log(res.data);
        if (res.data.ret == 1 && res.data.info != null) {
        	$scope.ports = res.data.info;
        	if (res.data.info.length > 0) {
             $scope.first_port = res.data.info[0].port;
       	  }
        }
	});
	// $http.get(baseurl+'/device_types/2').then(function(res){
	// 	console.log(res.data);
	// })
	// 下发查询的配置
    //配置分页基本参数
	$scope.paginationConf = {
	    currentPage: 1,
	    itemsPerPage: 10,
	    pagesLength: 5,
	    totalItems: 20,
	    perPageOptions: [10, 20, 30, 40, 50],
        projectid:'',
        deviceid:'',
        type:'',
	    onChange: function () {
	    }
	};
	// $scope.userid = $cookieStore.get('userid');
	// 切换页面布局
	$scope.table_show = false;
	$scope.jiazai = true;
	$scope.more_data = false;
	$scope.change_layout = function(){
         if ($scope.table_show == true) {
         	$scope.table_show = false;
         	$scope.jiazai = true;
         }else{
         	$scope.table_show = true;
         	$scope.jiazai = false;
         	$scope.paginationConf.projectid = '';
            $scope.paginationConf.deviceid = '';
         }
         $scope.select();
	}
	$scope.cur_page = 1;
	$scope.cur_rows = 9;
	$scope.select = function () {
        var page_obj = {};
		if ($scope.jiazai == true) {
			page_obj.page = $scope.cur_page;
			page_obj.rows = $scope.cur_rows;            
		}else{
            page_obj.page = $scope.paginationConf.currentPage;
			page_obj.rows = $scope.paginationConf.itemsPerPage;
		}
		var projectid = $scope.paginationConf.projectid;
		var deviceid = $scope.paginationConf.deviceid;
		var type = $scope.paginationConf.type;
		var query = '?projectid=='+projectid+'&deviceid='+deviceid+'&type='+type;
		// console.log(page_obj);
		$http.post(baseurl+'/list/select/view_device_project'+query,page_obj).then(function(res){
			  console.log(res.data);
			if (res.data.ret == 1) {
				if (res.data.rows != null) {
					for (var i = 0; i < res.data.rows.length; i++) {
						var obj = res.data.rows[i];
						obj.typename = $scope.type_obj[obj.type];
						if (obj.status == '0') {
							obj.statusname = '异常';
							obj.class_status = 'status_error';
						}else{
							obj.statusname = '正常';
							obj.class_status = 'status_normal';
						}						
					}
					// console.log(res.data.rows);				
					if ($scope.jiazai == true) {
                        if (res.data.rows < 1 && $scope.more_data == true) {
                        	new Notify('info','没有更多数据了'); 
                        }else{
                        	if ($scope.cur_page == 1) {
                               $scope.datas = res.data.rows; 
                        	}else{
                               var a = $scope.datas;
	                           var c = a.concat(res.data.rows);
	                           $scope.datas = c;
                        	}                        	
                        }
					}else{
						$scope.datas = res.data.rows;
				        $scope.paginationConf.totalItems = res.data.records;
					}						
				}
				
			}			
		})
	}
	$http.get(baseurl+'/select_idname/project').then(function(res){
		if(res.data.ret == 1){
			$scope.projects = res.data.info;
		}
	})
	// 按设备类型搜索
	$scope.select_type = function(id){
		$(".typespan").removeClass('badge');
		if ($scope.paginationConf.type === id) {
            $scope.paginationConf.type = '';
		}else{
			$(".typespan"+id).addClass('badge');
            $scope.paginationConf.type = id;
		}		
		$scope.cur_page = 1;
		$scope.more_data = false;
		$scope.select();
	}
	// 按项目类型搜索
	$scope.select_pro = function(id){
		$(".prospan").removeClass('badge');
		if ($scope.paginationConf.projectid === id) {
            $scope.paginationConf.projectid = '';
		}else{
			$(".prospan"+id).addClass('badge');
            $scope.paginationConf.projectid = id;
		}
		$scope.cur_page = 1;		
		$scope.more_data = false;
		$scope.select();
	}
	//add
	$scope.show_addbox = function(){
		$scope.insert = {};
		$scope.insert.projectid = '0';
		$scope.insert.port = $scope.first_port+'';
		$scope.insert.type = $scope.first_type;
	}
	$scope.insertdata = function () {
		if ($scope.insert.clientname == null || $scope.insert.clientname == '') {
            new Notify('info','客户名称不为空'); 
            return;
        }
        if ($scope.insert.devicename == null || $scope.insert.devicename == '') {
            new Notify('info','设备名称不为空'); 
            return;
        }
		if ($scope.insert.deviceid == null || $scope.insert.deviceid == '') {
            new Notify('info','设备号不为空'); 
            return;
        }
        if ($scope.insert.port == null || $scope.insert.port == '') {
            new Notify('info','端口号不为空'); 
            return;
        }
        
	    $http.post(baseurl+'/data/device',$scope.insert).then(function(res){
            // console.log(res.data);
	        if (res.data.ret == 1) {
	            $("#addModal").modal("hide");
            	 new Notify('success','添加成功');
            	 $scope.select();
            }else if (res.data.ret != -4){
	             new Notify('fail','设备号已存在');
	        }
    	});
	}
    //del
	$scope.showDelDialog = function (id) {
	    console.log(id);
	    $scope.delid= id;
	    $('#showDelDialog').modal('show');

	}
	$scope.deldevice = function () { 
	        $http.delete(baseurl+'/data/device?id=='+$scope.delid).then(function(res){
	             console.log(res.data);
	            if (res.data.ret == 1) {
	                $('#showDelDialog').modal('hide');
	                new Notify('success', '删除成功');
	            	 $scope.select();
	            }
	    	});
	}
	//edit
	$scope.editdata = {};
	$scope.showEditDevice = function (data) {
	    $scope.editid = data.id;
	    $scope.editdata.clientname = data.clientname;
	    $scope.editdata.devicename = data.devicename;
	    $scope.editdata.deviceid = data.deviceid;
	    $scope.editdata.port = data.port;
	    $scope.editdata.zone = data.zone;
	    $scope.editdata.pos = data.pos;
	    $scope.editdata.projectid = data.projectid+'';
	    $scope.editdata.type = data.type;
	    $('#editModal').modal('show');
        console.log(data,$scope.editid )
	};
	$scope.updatedata = function () {
		if ($scope.editdata.clientname == null || $scope.editdata.clientname == '') {
            new Notify('info','客户名称不为空'); 
            return;
        }
        if ($scope.editdata.devicename == null || $scope.editdata.devicename == '') {
            new Notify('info','设备名称不为空'); 
            return;
        }
		if ($scope.editdata.deviceid == null || $scope.editdata.deviceid == '') {
            new Notify('info','设备号不为空'); 
            return;
        }
        if ($scope.editdata.port == null || $scope.editdata.port == '') {
            new Notify('info','端口号不为空'); 
            return;
        }
        $http.put(baseurl+'/data/device?id=='+$scope.editid,$scope.editdata).then(function(res){
            // console.log(res.data);
            if (res.data.ret == 1) {
            	 new Notify('success','修改成功');
            	 $("#editModal").modal("hide");
            	 $scope.select();
            }
    	});
	};
	$scope.querydata = {};
	$scope.showQueryDialog = function (deviceid,port) {
	    // console.log(deviceid);
	    $scope.realdata = {};
	    $scope.queryport = port;
	    $scope.querydata.deviceid = deviceid;
	    $('#queryDialog').modal('show');
	    // 查询该类型设备的参数
	    $http.get('/list_nopage/device_parameters?type==2&pro_type=='+port).then(function(res){
	    	// console.log(res.data);
	    	if (res.data.ret == 1) {
	    		var arr = res.data.info;
	    		$scope.reals = arr;
	    	}
	    })	    
	}
	// 下发查询
	$scope.querydevice = function ()
	{
	    // console.log($scope.querydata,$scope.queryport);
	    var len = Object.keys($scope.reals).length;
	    if (len < 1) {
	    	new Notify('info','没有查询字段');
	    	return;
	    }
        $http.post(baseurl+'/query_device/'+$scope.queryport,$scope.querydata).then(function(res){
             // console.log(res.data);
             if (res.data.ret == 1 && res.data.info != null) {
             	var arr = res.data.info;
             	var obj = {};
             	for (var key in arr) {             		
             		obj[key] = arr[key];
             		if (typeof obj[key] ==="number") {
	             		obj[key] = obj[key].toFixed(2);
	             	}
             	}
             	
             	$scope.realdata = obj;
             }else{
             	new Notify('fail','没有查到数据');
             }
        });
	}
	function isJSON(str) {
	    if (typeof str == 'string') {
	        try {
	            var obj = JSON.parse(str);
	            return true;
	        } catch(e) {
	            return false;
	        }
	    }else{
	        return false;
	    }
	}
	// 控制参数
	$scope.showControlDialog = function(item){
		$scope.control_para = {};
		$('#conDialog').modal('show');
		$scope.editport = item.port;
		$scope.edit_id = item.id;
		$scope.edit_deviceid = item.deviceid;
		var json_obj = {};
		if (isJSON(item.para_control) == true) {
			json_obj = JSON.parse(item.para_control);
		}		
	    // 查询该类型设备的参数
	    $http.get('/list_nopage/device_parameters?type==3&pro_type=='+item.port).then(function(res){
	    	// console.log(res.data);
	    	if (res.data.ret == 1) {
	    		var arr = res.data.info;
	    		$scope.con_pars = arr;
	    		if (arr.length < 1) {
                    $scope.alert_info = item.port+'端口的设备没有控制参数';
	    		}else{
	    			$scope.alert_info = '';
                    for (var i = 0; i < arr.length; i++) {
		    			var key1 = arr[i]['key1'];
		    			if (json_obj != null && json_obj[key1] != null ) {
	                       $scope.control_para[key1] = json_obj[key1];
		    			}
		    		}
	    		}	    		
	    	}
	    })
	}
	$scope.conParameters = function(){
		var len = Object.keys($scope.control_para).length;
        var data = {
            para_control: JSON.stringify($scope.control_para)
        }
	    if(len > 0){
			$http.put(baseurl+"/edit_device/"+$scope.editport+"?id=="+$scope.edit_id+"&deviceid=="+$scope.edit_deviceid,data).then(function(res){
				// console.log(res.data)
				if(res.data.ret == 1){
					new Notify('success','发送成功');
					$scope.select();
				}else if(res.data.ret != -4){
					new Notify('fail','发送失败');
				}
				$('#conDialog').modal('hide');
			})
		}else{
			new Notify('fail','没有数据');
		}
	}
	$scope.control_device = function(value){
        var data = {
            para_control: value
        }
		$http.put(baseurl+"/edit_device/"+$scope.editport+"?id=="+$scope.edit_id+"&deviceid=="+$scope.edit_deviceid,data).then(function(res){
			// console.log(res.data)
			if(res.data.ret == 1){
				if (res.data.status == 1) {
					new Notify('success','控制成功');
				}else if (res.data.status == 0) {
					new Notify('fail','设备不在线，控制失败');
				}				
				$scope.select();
			}else if(res.data.ret != -4){
				new Notify('fail','发送失败');
			}
			$('#conDialog').modal('hide');
		})
	}
    // 参数设置
	$scope.data = {};
	// 参数值
	$scope.parameters = {};
	// 是否选中
	$scope.parametercheck = {};
	// 最后发送的选中值
	$scope.sendparameter = {};
	$scope.showSetDialog = function (item) {
		$('#setDialog').modal('show');
		$scope.setport = item.port;
		$scope.edit_id = item.id;
		$scope.edit_deviceid = item.deviceid;
		var json_obj = {};
		if (isJSON(item.para_set) == true) {
			json_obj = JSON.parse(item.para_set);
		}
	    // 查询该类型设备的参数
	    $http.get('/list_nopage/device_parameters?type==1&pro_type=='+item.port).then(function(res){
	    	// console.log(res.data);
	    	if (res.data.ret == 1) {
	    		var arr = res.data.info;
	    		$scope.pars = arr;
	    		if (arr.length < 1) {
                    $scope.alert_info = item.port+'端口的设备没有配置参数';
	    		}else{
	    			$scope.alert_info = '';
                    for (var i = 0; i < arr.length; i++) {
		    			var key1 = arr[i]['key1'];
		    			if (json_obj != null && json_obj[key1] != null ) {
	                       $scope.parameters[key1] = json_obj[key1];
	                       $scope.parametercheck[key1] = false;
		    			}
		    		}
	    		}	    		
	    	}
	    })
    }
    // 设置参数
	$scope.setParameters = function () {
		// console.log($scope.parametercheck,$scope.parameters)
		for (var key in $scope.parametercheck) {
			if ($scope.parametercheck[key] == true) {
				$scope.sendparameter[key] = $scope.parameters[key];
			}
		}
        var len = Object.keys($scope.sendparameter).length;
        var data = {
            para_set: JSON.stringify($scope.sendparameter)
        }
	    if(len > 0){
			$http.put(baseurl+"/edit_device/"+$scope.setport+"?id=="+$scope.edit_id+"&deviceid=="+$scope.edit_deviceid,data).then(function(res){
				// console.log(res.data)
				if(res.data.ret == 1){
					if (res.data.status == 1) {
						new Notify('success','设置成功');
					}else if (res.data.status == 0) {
						new Notify('fail','设备不在线，设置失败');
					}
					$scope.select();
				}else if(res.data.ret != -4){
					new Notify('fail','发送失败');
				}
				$('#setDialog').modal('hide');
			})
		}else{
			new Notify('fail','没有选中数据');
		}
	}
	$scope.$watch('paginationConf.currentPage + paginationConf.itemsPerPage', $scope.select);
	
	// 加载更多
	$scope.jiazai_more = function(){
         $scope.cur_page += 1;
         $scope.more_data = true;
         $scope.select();
	}
});
